#include <iostream>
#include <functional>
#include <cstdio>
#include <cstring>
#include <unistd.h>
#include<pthread.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include "err.hpp"
#include"ThreadPool.hpp"
#include"Task.hpp"

namespace ns_server
{

    using func_t = std::function<std::string(std::string)>;
    const static int backlog = 32;
    
    class tcpServer;
    class ThreadDate
    {
    public:
        ThreadDate(int sock,std::string clientIp,uint16_t clientPort,tcpServer*ts)
        :_sock(sock),
        _clientIp(clientIp),
        _clientPort(clientPort),
        _ts(ts)
        {}
    public:
        int _sock;
        std::string _clientIp;
        uint16_t _clientPort;
        tcpServer*_ts;
    };

    class tcpServer
    {
    public:
        tcpServer(uint16_t port, func_t func) : _port(port), _func(func)
        {
        }

        void Init()
        {
            // 1.创建套接字
            _listenSock = socket(AF_INET, SOCK_STREAM, 0);
            if (_listenSock < 0)
            {
                std::cerr << "socket error" << std::endl;
                exit(SOCKET_ERR);
            }
            // 2.bind套接字结构体
            struct sockaddr_in local;
            local.sin_family = AF_INET;
            local.sin_port = htons(_port);
            local.sin_addr.s_addr = INADDR_ANY;
            socklen_t len = sizeof(local);

            if (bind(_listenSock, (struct sockaddr *)&local, len) < 0)
            {
                std::cerr << "bind error" << std::endl;
                exit(BIND_ERR);
            }

            // 3.创建监听

            if (listen(_listenSock, backlog) < 0)
            {
                std::cerr << "listen error" << std::endl;
                exit(LISTEN_ERR);
            }
        }

        void Start()
        {
            // 4.等待连接
            while (!quit)
            {
                struct sockaddr_in client;
                socklen_t len = sizeof(client);
                memset(&client, 0, sizeof(client));
                _sock = accept(_listenSock, (struct sockaddr *)&client, &len);
                if (_sock < 0)
                {
                    std::cerr << "accept error" << std::endl;
                    continue;
                }
                std::cout << "aceept sucess: " << _sock << " form " << _listenSock << std::endl;

                // 提取client信息
                std::string clientIp = inet_ntoa(client.sin_addr);
                uint16_t clientPort = ntohs(client.sin_port);

                // //一.多进程版本
                // pid_t id=fork();
                // if(id<0)
                // {
                //     close(_sock);
                //     continue;
                // }
                // else if(id==0)
                // {
                //     //子进程
                //     //建议关闭不需要的fd
                //     close(_listenSock);
                //     if(fork()>0)exit(0);
                //     //孙子进程
                //     service(_sock,clientIp,clientPort);
                //     exit(0);
                // }

                // //父进程    
                // //一定关闭不需要的fd，不然会造成fd泄漏
                // close(_sock);

                // //二. 多线程
                // pthread_t tid;
                // ThreadDate*ts=new ThreadDate(_sock,clientIp,clientPort,this);
                // pthread_create(&tid,nullptr,threadRoutine,ts);

                //三. 线程池版本
                Task t(_sock,clientIp,clientPort,std::bind(&tcpServer::service,this,std::placeholders::_1,std::placeholders::_2,std::placeholders::_3));

                ThreadPool<Task>::getInstance()->pushTask(t);
            }
        }

        static void*threadRoutine(void*args)
        {
            //线程分离
            pthread_detach(pthread_self());
            ThreadDate*ts=static_cast<ThreadDate*>(args);
            ts->_ts->service(ts->_sock,ts->_clientIp,ts->_clientPort);
            delete ts;
            return nullptr;
        }

        void service(int sock, std::string clientIp, uint16_t clientPort)
        {
            std::string who = clientIp + std::to_string(clientPort);
            while (true)
            {
                // 5. 收消息
                char buffer[1024];
                int n = read(sock, buffer, sizeof(buffer) - 1);
                if (n > 0)
                {
                    // 成功读取到消息，执行业务
                    buffer[n] = '\0';
                    std::string message = _func(buffer);
                    std::cout<<who<<" >>> "<<message<<std::endl;

                    write(sock,message.c_str(),message.size());
                }
                else if (n == 0)
                {
                    // 客户端关闭
                    close(_sock);
                    std::cout << who << " quit" << std::endl;
                    break;
                }
                else
                {
                    // 读取异常
                    std::cerr << "read error" << std::endl;
                    break;
                }
            }
        }

        ~tcpServer()
        {
        }

    private:
        uint16_t _port;
        int _listenSock;
        int _sock;
        func_t _func;
        bool quit = false;
    };
}